<template>
  <div>
    <div style="display: flex;margin-top: 10px;">
      <el-button @click="print" :loading="loading" type="primary">开始打印</el-button>
      <el-input v-model="pdfNum" style="width: 200px;"></el-input>
      <div style="margin-left: 20px;">
        <el-radio v-model="radio" label="1" :disabled="printShow" border>word</el-radio>
        <el-radio v-model="radio" label="2" :disabled="printShow" border>pdf</el-radio>
      </div>
    </div>
    <div v-if="printShow" id="playerDetailPrint" style="width: 600px;padding:50px 50px 50px 50px;overflow: visible;">
      <otherPlanPrint id="myPrint" :previewData="printData" :docClassId="currentDocClassId" />
    </div>
  </div>
</template>

<script>
  import html2Canvas from 'html2canvas'
  import JsPDF from 'jspdf'
  // import VueHtml2pdf from 'vue-html2pdf'
  import {
    plan_doc_all,
    allType,
    moralityEducation,
    batchPrint
  } from '@/api/plan.js'
  import {
    sport_by_org,
    currentRoleEmployee,
    plan_doc_available
  } from '@/api/dict.js'
  import htmlDocx from 'html-docx-js/dist/html-docx';
  import saveAs from 'file-saver';
  import otherPlanPrint from "@/components/print/otherPlanPrint.vue"
  export default {
    components: {
      otherPlanPrint,
    },
    data() {
      return {
        printData: {},
        defaultData: [],
        fileName: '',
        download: false,
        pdfSave: 1,
        pdfNum: 0,
        currentDocClassId: 41,
        dict_sport: {},
        dict_emp: {},
        nameArr: [],
        dict_docClass: {},
        loading: false,
        printShow: false,
        docDataIdArr: [],
        radio: '1',
      }
    },
    computed: {
      pdfOptions() {
        return {
          margin: [0, 5, 0, 5],
          pagebreak: {
            mode: 'avoid-all'
          }
        }
      },
    },
    created() {
      this.pdfNum = window.localStorage.getItem('educationPdfNum')
      if(!this.pdfNum) this.pdfNum = 0
      this.init_dict()
    },
    watch: {},
    methods: {
      init_dict() {
        this.loading = true
        return new Promise((resolve, reject) => {
          moralityEducation().then(res => {
            if (res.code === 200 && res.data.length != 0) {
              res.data.forEach(item=>{
                this.docDataIdArr.push(item.docDataId)
              })
              batchPrint({docDataIds:this.docDataIdArr.join(',')}).then(res=>{
                if(res.code === 200) {
                  this.defaultData = res.data
                }else{
                  this.defaultData = []
                }
                this.loading = false
                resolve()
              })
            }
          })
        })
      },
      print() {
        window.localStorage.setItem('educationPdfNum',this.pdfNum)
        if (this.defaultData.length == 0) {
          this.$message.error('没有数据怎么打印？！！！')
          return
        }
        if (this.pdfNum != this.defaultData.length) {
          this.playerDetailPrint(this.defaultData[this.pdfNum])
        }
      },
      playerDetailPrint(item) {
          this.printData = item[this.currentDocClassId]
          this.printShow = true
          let timmer = setTimeout(()=>{
            let dom = document.getElementById('playerDetailPrint')
            let count = ''
            let planName = Object.keys(item[this.currentDocClassId])[3]
            this.nameArr.push(planName)
            let num = 0
            this.nameArr.forEach(item => {
              if (item == planName) {
                num++
              }
            })
            count = (num).toString()
            if (count.length == 1) {
              count = '-00' + count
            } else if (count.length == 2) {
              count = '-0' + count
            } else {
              count = '-' + count
            }
            if(this.radio=='1'){
              this.getWordFromHtml(dom, planName + count)
            }else if(this.radio=='2'){
              this.getPdfFromHtml(dom, planName + count)
            }
            clearTimeout(timmer)
          },1000)
      },
      getWordFromHtml(ele, pdfFileName) {
        const divEl = document.getElementById('playerDetailPrint')
        let page = `<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>${divEl.innerHTML}</body></html>`
        const converted = htmlDocx.asBlob(page);
        saveAs(converted, pdfFileName+'.docx')
        this.printShow = false
        this.pdfNum = parseInt(this.pdfNum)
        this.pdfNum += 1
        this.print()
      },
      getPdfFromHtml(ele, pdfFileName) {
        html2Canvas(ele, {
          dpi: window.devicePixelRatio * 4,
          scale: 4,
          useCORS: true, //允许canvas画布内可以跨域请求外部链接图片, 允许跨域请求。
          allowTaint: false,
          height: ele.offsetHeight,
          width: ele.offsetWidth,
          windowWidth: document.body.scrollWidth,
          windowHeight: document.body.scrollHeight,
        }).then(canvas => {
          this.dialogVisible = true;
          const _this = this;
          //未生成pdf的html页面高度
          var leftHeight = canvas.height;
          var a4Width = 595.28
          var a4Height = 841.89
          //一页pdf显示html页面生成的canvas高度;
          var a4HeightRef = Math.floor(canvas.width / a4Width * a4Height);

          //pdf页面偏移
          var position = 0;

          var pageData = canvas.toDataURL('image/jpeg', 1.0);

          var pdf = new JsPDF('x', 'pt', 'a4');
          var index = 1,
            canvas1 = document.createElement('canvas'),
            height;
          pdf.setDisplayMode('fullwidth', 'continuous', 'FullScreen');

          // $('.head-content').append($(
          //   '<div class="pdfTip">' +
          //   '   <div>正在生成第<span class="pdfProgress">1</span>页，共<span class="pdfTotal"></span>页...' +
          //   '</div>'));
          function createImpl(canvas) {
            if (leftHeight > 0) {
              index++;
              var checkCount = 0;
              if (leftHeight > a4HeightRef) {
                var i = position + a4HeightRef;
                for (i = position + a4HeightRef; i >= position; i--) {
                  var isWrite = true
                  for (var j = 0; j < canvas.width; j++) {
                    var c = canvas.getContext('2d').getImageData(j, i, 1, 1).data

                    if (c[0] != 0xff || c[1] != 0xff || c[2] != 0xff) {
                      isWrite = false
                      break
                    }
                  }
                  if (isWrite) {
                    checkCount++
                    if (checkCount >= 10) {
                      break
                    }
                  } else {
                    checkCount = 0
                  }
                }
                height = Math.round(i - position) || Math.min(leftHeight, a4HeightRef);
                if (height <= 0) {
                  height = a4HeightRef;
                }
              } else {
                height = leftHeight;
              }

              canvas1.width = canvas.width;
              canvas1.height = height;

              // console.log(index, 'height:', height, 'pos', position);

              var ctx = canvas1.getContext('2d');
              ctx.drawImage(canvas, 0, position, canvas.width, height, 0, 0, canvas.width, height);

              var pageHeight = Math.round(a4Width / canvas.width * height);
              // pdf.setPageSize(null, pageHeight)
              if (position != 0) {
                pdf.addPage();
              }
              pdf.addImage(canvas1.toDataURL('image/jpeg', 1.0), 'JPEG', 0, 20, a4Width, a4Width / canvas1.width *
                height);
              leftHeight -= height;
              position += height;
              // $('.pdfProgress').text(index + 1);
              // $('.pdfTotal').text(index + Math.ceil(leftHeight / a4HeightRef));
              if (leftHeight > 0) {
                //添加全屏水印
                // const base64 = ''
                // for(let i=0;i<6;i++){
                //   for(let j=0;j<5;j++){
                //     const  left = (j*120)+20;
                //     pdf.addImage(base64,'JPEG', left, i*150, 20, 30);
                //   }
                // }
                setTimeout(createImpl, 500, canvas);
              } else {
                // _this.iframeSrc = pdf.output('dataurlstring');
                // debugger;
                this.pdfSave = pdf.save(pdfFileName + '.pdf');
              }
            }
          }

          //当内容未超过pdf一页显示的范围，无需分页
          if (leftHeight < a4HeightRef) {
            pdf.addImage(pageData, 'JPEG', 0, 0, a4Width, a4Width / canvas.width * leftHeight);
            this.dialogVisible = true;
            // this.iframeSrc = pdf.output('dataurlstring');
            // debugger;
            this.pdfSave = pdf.save(pdfFileName + '.pdf')
          } else {
            try {
              pdf.deletePage(0);
              // $('.pdfTip').show();
              // $('.pdfTotal').text(index + Math.ceil(leftHeight / a4HeightRef));
              setTimeout(createImpl, 500, canvas);

            } catch (err) {
              console.log(err);
            }
          }
        }).then(() => {
          this.printShow = false
          this.pdfNum = parseInt(this.pdfNum)
          this.pdfNum += 1
        }).then(() => {
          this.print()
        })

      },
    }
  }
</script>

<style scoped>

</style>
